package per.wsj.room.ui.main

import androidx.lifecycle.ViewModelProviders
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import kotlinx.android.synthetic.main.main_fragment.*
import per.wsj.room.R
import per.wsj.room.data.entity.User

class MainFragment : Fragment() {

    companion object {
        fun newInstance() = MainFragment()
    }

    private lateinit var viewModel: MainViewModel

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return inflater.inflate(R.layout.main_fragment, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)

        btn1.setOnClickListener {
            val user = User()
            user.name = "小花2"
            user.sex = 2
            user.age = 27
            viewModel.addUser2(user)
        }

        btn2.setOnClickListener {
            val users = viewModel.getUsers()
            users.observe(viewLifecycleOwner, Observer<List<User>> {
                it.forEach { item ->
                    Log.e("aaaa", item.toString())
                }
            })
        }

    }

}
